<template>
	<div class="main">
		<div class="wrapper">
			<div class="progressBox">
				<div class="progress" :style="{width:progressWidth+'px'}"></div>
			</div>
			<div class="item">
				<div style="display:flex;line-height:50px;position:relative">
					<span class="no_wrap">{{question.current}}&nbsp;、{{question.detail.questionContent}}</span>
          <span v-if="question.current===21" style="color:#ff6b6b;">(kg)</span>
          <span v-if="question.current===20" style="color:#ff6b6b;">(cm)</span>
					<!-- Checkbox and Radio -->
					<div style="text-align:left;" v-if="question.detail.type===1 || question.detail.type===2">
						（<span ref="select" class="right-blue">{{currentResult2Format}}</span>）
						<span v-if="isMultiOption" style="color:#ff6b6b;">(可多选)</span>
						<ul :class="{flex:question.options.length>8}" style="position:absolute;left:0;white-space: nowrap;">
							<li v-for="item in question.options" @click="onOptionsClick(item)"
									class="lis" ref="nodes">{{item.answerContent}}
							</li>
						</ul>
          </div>
          <!--第十七、十八题-->
          <div style="text-align:left;" v-if="question.detail.type===5">
            （<span ref="select" class="right-blue">{{currentResult2Format}}</span>）
            <span v-if="isMultiOption" style="color:#ff6b6b;">(可多选)</span>
            <ul :class="{flex:question.options.length>8}" style="position:absolute;left:0;white-space: nowrap;">
              <li v-for="item in question.options" @click="onOptionsClick(item)"
                  class="lis" ref="nodes">{{item.answerContent ? item.answerContent : item.name}}
              </li>
            </ul>
            <!--输入框-->
            <el-input
              class="text_npt"
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              >
            </el-input>
          </div>
          <!-- Select -->
					<el-input
                      type="textarea" v-else-if="question.detail.type===3 && question.detail.questionId!=19"
           v-model="result[question.current - 1]"
                           autosize
                  :placeholder="question.detail.inputLabel"
                  style="padding:6px;float: left; margin-right:40px;">
                 </el-input>
					<!--input v-else-if="question.detail.type===3 && question.detail.questionId!=19" type="text" class="edito"
							v-model="result[question.current - 1]"
							:placeholder="question.detail.inputLabel"/-->
					<!--年龄选择特有 判断题目是19-->
				    <el-date-picker v-else-if="question.detail.questionId==19"
	                    v-model="result[question.current - 1]"
	                    align="right"
	                    value-format="yyyy/MM/dd"
	                    type="date"
	                    :placeholder="question.detail.inputLabel"
	                  >
	                </el-date-picker>
					<textarea v-else-if="question.detail.type===4" :placeholder="question.detail.inputLabel"
							v-model="result[question.current - 1]"
							style=" width:100%;padding:6px;float: left;color:#3c3c3c; margin-top: 40px; margin-bottom: 0px; height: 114px;"></textarea>
					<!--Select -->
					<template v-else-if="question.detail.type===6">
						<Row style="width: 600px;">
							<Col span="12" style="padding-right:10px">
                <el-select ref="select" v-model="result[question.current - 1]"
                                             multiple
                                             filterable
                                            allow-create
                                             default-first-option
                                             :remote-method="reloadLoadOptions"
										     :placeholder="question.detail.inputLabel">
                                        <el-option
                                          v-for="item in question.options"
												    :label="item.label"
												 :value="item.name || item.answerContent"
                                                :key="item.__key__">{{ item.name || item.answerContent }}

                                                                          </el-option>
                                                                            </el-select>
							</Col>
						</Row>
					</template>
          <!-- Cascader -->
					<template v-else-if="question.detail.type===7">
						<Row style="width: 600px;">
							<Col span="12" style="padding-right:10px">
								<el-cascader :options="question.options"
										v-model="result[question.current - 1]"
										@active-item-change="reloadLoadOptions"
								></el-cascader>
							</Col>
						</Row>
					</template>
				</div>
			</div>

			<div class="btnbox">
				<div class="itemStyle" slot="button-prev" v-if="question.current>1" @click="prevQuestion">上一题</div>
				<div class="itemStyle" slot="button-next" @click="nextQuestion">
					{{question.current===22?'提交':'下一题'}}
				</div>
			</div>

		</div>
	</div>
</template>
<script>
	import Service from "@/service/service";

	export default {
		name: "TestTopic",
		props: {},
		data() {
			return {
				question: {
					// 当前题目
					current: 22,
					// 题目内容
					detail: {},
					// 题目选项
					options: [],
				},
				//存放的结果
				result: [],
			};
		},
		//计算属性
		computed: {
			progressWidth() {
				return this.question.current * 50;
			},
			isMultiOption() {
				return this.question.detail.type === 2;
			},
			currentResult() {
				return this.result[this.question.current - 1];
			},
			currentResult2Format() {
				const result = this.currentResult;
				if (result instanceof Array) {
					return result.join(',');
				} else {
					return result;
				}
			},
		},
		//组件被创建
		created() {
			this.getQuestion();
		},
		methods: {
			// 加载扩展题目数据
			loadServiceOptions(value = '') {
				const tree = function(data, pid = 0) {
					const result = [];
					for (let i = 0; i < data.length; i++) {
						const item = data[i];
						if (pid === item.parentId) {
							data.splice(i, 1);
							delete item.parentId;
							result.push(item);
							i--;

							const children = tree(data, item.value);
							if (children.length) {
								item.children = children;
							}
						}
					}
					return result;
				};

				let url = this.question.detail.serviceUrl;
				if ([14, 15].indexOf(this.question.current) !== -1) {
					url = url.replace('/user/', '/test/')
				}

				const data = {
					keyword: value,
					param: {
						detail: {
							questionId: this.question.detail.questionId
						},
					},
				};

				if (14 === this.question.current) {
					data.pageNo = 1;
					data.pageSize = 20;
				} else if (15 === this.question.current) {
					data.param.pageNo = 1;
					data.param.pageSize = 20;
				} else if (16 === this.question.current) {
					if (value) data.param.detail.parentId = value[0];
				}

				return Service.myAjax({
					method: "post",
					url: Service.baseUrl + url,
					data: data
				}, (response) => {
					return response.data.data.list.map((item) => {
						item.__key__ = item.id + '_' + new Date().getTime();
						return item;
					});
				}).then((data) => {
					if (this.question.current === 16) {
						data = data.map((item) => {
							const result = {
								value: item.answerId,
								label: item.answerContent,
								parentId: parseInt(item.parentId),
							};
							if (!value) result.children = [];
							return result;
						});
						return data;
						// return tree(data);
					}
					return data;
				});
			},
			// 加载题目数据
			loadDefaultOptions() {
				return Service.myAjax({
					method: "post",
					url: Service.baseUrl + "/test/getAnswersOfQuestion",
					data: {
						param: {
							detail: {
								parentId: "0",
								questionId: this.question.detail.questionId
							}
						},
					}
				}, (response) => {
					return response.data.data.list;
				});
			},
			// 加载题目选项数据
			loadOptions(value) {
				return this.question.detail.serviceUrl ? this.loadServiceOptions(value) : this.loadDefaultOptions(value);
			},
			// 重新加载数据
			reloadLoadOptions(value) {
				if (16 === this.question.current) {
					if (value.length > 1) return;
					this.loadOptions(value).then((options) => {
						if (value) {
							const item = this.question.options.find(it => it.value === value[0]);
							if (item) this.$set(item, 'children', options);
						} else {
							this.question.options = options;
						}
					});
				} else {
					this.loadOptions(value).then(options => this.question.options = options);
				}
			},
			// 加载题目
			getQuestion() {
				Service.myAjax({
					method: "post",
					url: Service.baseUrl + "/test/questionDetail",
					data: {
						extra: {},
						keyword: "沈阳",
						orderBy: "string",
						pageNo: "string",
						pageSize: "string",
						param: {
							detail: {
								questionId: this.question.current
							}
						},
						password: "",
						userId: "127"
					}
				}, (response) => {
					this.question.detail = response.data.data.detail;
					const current = this.question.current - 1;
					if (this.result[current] === undefined) {
						let value = '';
						if ([2, 7,].indexOf(this.question.detail.type) !== -1) {
							value = [];
						}
						this.$set(this.result, current, value);
						this.$nextTick(function() {
							if (this.$refs.select) {
								this.$refs.select.query = '';
							}
						});
					}
					return this.loadOptions();
				}).then((options) => {
					this.question.options = options;
          console.log(this.question.options);
        });
			},
			// 上一个题目
			prevQuestion() {
				this.question.current--;
				this.question.options = [];

				this.getQuestion();
				console.log(this.question.current);
			},
			// 下一个题目
			nextQuestion() {
				const currentResult = this.currentResult;
				if (!currentResult || !currentResult.length) {
					this.$message.error('请选择');
					return;
				}

				// 如果是最后一题
				if (this.question.current === 22) {
					this.submit();
					return;
				}

				this.question.current++;
				this.question.options = [];

				this.getQuestion();
				console.log(this.question.current);
			},
			// 题目选项被点击
			onOptionsClick(item) {
				const current = this.question.current - 1;
				const value = item.answerContent.split("、")[0];
				if (this.isMultiOption) { //多选
					if (!this.result[current]) {
						this.$set(this.result, current, []);
					}

					const index = this.result[current].indexOf(value);
					if (index === -1) {
						this.result[current].push(value);
					} else {
						this.result[current].splice(index, 1);
					}

				} else { //单选
					this.$set(this.result, current, value);
				}
			},
			// 提交选题
			submit() {
			},
		},
		watch: {}
	};
</script>
<style lang="stylus" scoped>
	@import '~styles/variables';

	.main {
		font-size: 16px;
	}

	.wrapper >>> .swiper-pagination-progress {
		width: 10rem;
		height: 0.3rem;
		left: 1.5rem;
		top: 0.5rem;
	}

	.wrapper >>> .swiper-pagination-progressbar {
		background: $ logoColor;
		box-shadow: 0 0.05rem 0.1rem #000000;
	}

	.wrapper >>> .swiper-button-next, .swiper-button-prev {
		background-size: auto;
		width: 1.88rem;
		opacity: 1;
	}

	.wrapper >>> .swiper-button-next {
		background-image: url('../../../assets/image/next.png');
	}

	.wrapper >>> .swiper-button-prev {
		background-image: url('../../../assets/image/prev.png');
	}

	.main {
		position: relative;
		width: 14rem;
		height: 7rem;
		margin-left: 2.6rem;
		margin-top: 0.35rem;
		background: #f5f5f5 url('../../../assets/image/qi.png') no-repeat right 0.68rem top;

	.wrapper {
		border: 1px solid transparent;
	}

	.item {
		display: flex;
		flex-direction: column;
		xbackground: red;
		justify-content: center;
		align-items: flex-start;
		margin-left: 1.5rem;
		margin-top: 0.5rem;
		width: 10rem;
		line-height: 26px;
	}

	li {
		line-height: 0.3rem;
		cursor: pointer;
		text-align: left;
	}

	.right-blue {
		color: #3b75f2;
		line-height: 0.5rem;
		//margin-right: 0.3rem;
	}

	}

	.progressBox {
		width: 1000px;
		height: 20px;
		margin-left: 1.5rem;
		margin-top: 50px;
		background: #CFCFCF;
		position: relative;
		overflow: hidden;
		border-radius:10px;
	}

	.progress {
		height: 50px;
		position: absolute;
		left: 0;
		background: #FACE39;
	}

	.btnbox {
		/*background: red;*/
		display: flex;
		position: absolute;
		/*background: #f00;*/
		display: flex;
		justify-content: center;
		align-items: center;
		left: 0;
		right: 0;
		margin: auto;
		bottom: 0.84rem;
		width: 5rem;
	}

	.itemStyle {
		padding: 15px;
		background: #FACE39;
		margin-right: 100px;
		z-index: 99999;
		cursor: pointer;
	}

	#ide {
		resize: none;
		margin-top: 24px;
		padding: 6px;
		height: 200px;
		width: 1000px;
		border: 2px solid yellow;
		background: rgba(255, 255, 255, 0.5);
	}

	.flex {
		width: 284px;
		max-height: 14em;
		overflow: auto;
		margin-top: 30px;
	}

	.lis {
		padding: 2px;

	}

	.lis:hover {
		color: #5eb95e;
	}

	.edito {
		background-color: transparent;
		border-bottom: 1px solid #adadad;
		color: #3c3c3c;
		padding-left: 10px;
	}
	.el-select{
		display:block;
	}
	.no_wrap{
		white-space:nowrap;
	}
  .text_npt{
    position:absolute;
    top:226px;
    left:0;
    width: 300px;

  }
</style>
